const electron = require('electron');
const ipcRenderer = electron.ipcRenderer;
const io = require('./io');
let publicfunc = require('./publicfunc');

let CurrentSoundPage = 0;
let SoundPageCount = 20;
let AudioSoundFiles;
let SoundTagTree;
let CurrentSoundMainTagButton;
let CurrentSoundChildTagButton;
let SoundFlags = false;
let SoundKey = 'sound';

function OnSoundPageChange(page, count) {
    CurrentSoundPage = page;
    SoundPageCount = count;
    publicfunc.RequestSearch(page, count, false, SoundFlags);
}

function OnSoundMainTagChange(btn) {
    if (CurrentSoundMainTagButton != undefined) {
        CurrentSoundMainTagButton.removeClass('active');
    }
    CurrentSoundMainTagButton = btn;
    CurrentSoundMainTagButton.addClass('active');
}

function SoundChildTagChange(btn) {
    if (CurrentSoundChildTagButton != undefined) {
        CurrentSoundChildTagButton.removeClass('active');
    }
    CurrentSoundChildTagButton = btn;
    CurrentSoundChildTagButton.addClass('active');
}

function RequestSoundSearch(isRefresh, isMusic) {
    publicfunc.RequestSearch(CurrentSoundPage, SoundPageCount, isRefresh, isMusic);
}

function RequestSoundNewTag(tag, isMusic) {    
    publicfunc.RequestNewTag(CurrentSoundMainTagButton.text(),CurrentSoundChildTagButton.text(),tag,isMusic);
}

function RegistSoundWS() {
    io.onwebsocket('search-{0}'.format(SoundKey), (data) => {
        AudioSoundFiles = data.results;
        publicfunc.UpdateResoucesShown(AudioSoundFiles, data.index, SoundTagTree, data.size, SoundPageCount, OnSoundPageChange, SoundFlags,'sound');
    });

    io.onwebsocket('gettaglist-{0}'.format(SoundKey), (data) => {
        SoundTagTree = data;
        publicfunc.UpdateMainTagsShown(SoundTagTree, OnSoundMainTagChange, SoundChildTagChange, RequestSoundSearch, SoundFlags);
    });
    publicfunc.RegistWS(SoundFlags);
}

function DownloadSounds(ids) {
    let files = new Array();
    for (let i = 0; i < ids.length; i++) {
        let file = publicfunc.GetFile(AudioSoundFiles, ids[i]);
        if (file != null) {
            files.push(file);
        }
    }
    ipcRenderer.send('downloadall', { baseurl: io.geturl(), files: files });
}

module.exports = {
    CurrentSoundPage,
    SoundPageCount,
}

io.websocketemit('login');
publicfunc.RegistClickEvents(SoundFlags, DownloadSounds, RequestSoundSearch, RequestSoundNewTag);
RegistSoundWS();
